import { useNavigate } from 'react-router-dom';
import { Triangle, Lock } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { logout as apiLogout, changePassword as apiChangePassword } from '../api/authApi';
import { useConfirm } from '../hooks/useConfirm';
import { useDialog } from '../hooks/useDialog';
import { useToast } from '../hooks/useToast';
import { Confirm } from './Confirm';
import { Dialog } from './Dialog';
import { ToastContainer } from './Toast';
import './AdminNav.css';

function AdminNav() {
  const navigate = useNavigate();
  const { username, token, logout } = useAuth();
  const { confirmState, showConfirm } = useConfirm();
  const { dialogState, showDialog } = useDialog();
  const toast = useToast();

  const handleLogout = async () => {
    const confirmed = await showConfirm({
      title: '退出登录',
      message: '确定要退出登录吗？',
      type: 'warning',
      confirmText: '退出',
      cancelText: '取消'
    });
    
    if (confirmed) {
      try {
        await apiLogout(token);
      } catch (error) {
        console.error('登出错误:', error);
      } finally {
        logout();
        navigate('/admin/login');
      }
    }
  };

  const handleChangePassword = async () => {
    const result = await showDialog({
      title: '修改密码',
      message: '请输入密码信息',
      fields: [
        {
          name: 'oldPassword',
          label: '当前密码',
          type: 'password',
          placeholder: '请输入当前密码',
          required: true
        },
        {
          name: 'newPassword',
          label: '新密码',
          type: 'password',
          placeholder: '请输入新密码（至少6位）',
          required: true,
          validate: (value) => {
            if (value.length < 6) {
              return '新密码长度至少6位';
            }
            return null;
          }
        },
        {
          name: 'confirmPassword',
          label: '确认新密码',
          type: 'password',
          placeholder: '请再次输入新密码',
          required: true,
          validate: (value, allValues) => {
            if (value !== allValues.newPassword) {
              return '两次输入的密码不一致';
            }
            return null;
          }
        }
      ],
      confirmText: '确认修改',
      cancelText: '取消'
    });
    
    if (!result) return;
    
    try {
      await apiChangePassword(token, result.oldPassword, result.newPassword);
      toast.success('密码修改成功！');
    } catch (error) {
      toast.error(error.message || '修改密码失败');
    }
  };

  return (
    <nav className="admin-nav">
      <div className="nav-content">
        <div className="nav-left">
          <button onClick={() => navigate('/admin')} className="nav-logo">
            <Triangle size={18} /> 几何模型管理系统
          </button>
        </div>
        <div className="nav-right">
          <span className="user-info">{username}</span>
          <button onClick={handleChangePassword} className="nav-btn change-password-btn" title="修改密码">
            <Lock size={16} />
            修改密码
          </button>
          <button onClick={handleLogout} className="nav-btn logout-btn">
            退出登录
          </button>
        </div>
      </div>
      
      {/* Confirm 对话框 */}
      {confirmState && <Confirm {...confirmState} />}
      
      {/* Dialog 对话框 */}
      {dialogState && <Dialog {...dialogState} />}
      
      {/* Toast 提示 */}
      <ToastContainer toasts={toast.toasts} removeToast={toast.removeToast} />
    </nav>
  );
}

export default AdminNav;

